package com.molichuxing.gateway.bff.user.services.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.gateway.bff.user.convertor.Convert;
import com.molichuxing.gateway.bff.user.entity.request.modify.DrivingLicenseModifyVo;
import com.molichuxing.gateway.bff.user.entity.response.DrivingLicenseVo;
import com.molichuxing.gateway.bff.user.services.DrivingLicenseBffService;
import com.molichuxing.services.business.dto.request.modify.DrivingLicenseBizModifyDto;
import com.molichuxing.services.business.dto.response.DrivingLicenseBizDto;
import com.molichuxing.services.business.service.SmsBizService;
import com.molichuxing.services.business.service.UserBizService;
import com.molichuxing.services.infrastructure.dto.request.create.MessageCenterCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.NotifyPushCreateDto;
import com.molichuxing.services.infrastructure.dto.response.DrivingLicenseDto;
import com.molichuxing.services.infrastructure.dto.response.MessageTemplateDto;
import com.molichuxing.services.infrastructure.dto.response.UserDto;
import com.molichuxing.services.infrastructure.service.DrivingLicenseService;
import com.molichuxing.services.infrastructure.service.MessageCenterService;
import com.molichuxing.services.infrastructure.service.MessageTemplateService;
import com.molichuxing.services.infrastructure.service.NotifyPushService;
import com.molichuxing.services.infrastructure.service.UserService;
import com.molichuxing.services.property.DrivingLicenseDataSourceEnum;
import com.molichuxing.services.property.DrivingLicenseStatusEnum;
import com.molichuxing.services.property.DrivingLicenseVerifyStatusEnum;
import com.molichuxing.services.property.MessageCenterStatusEnum;
import com.molichuxing.services.property.MessageCenterTypeEnum;
import com.molichuxing.services.property.SmsTemplateEnum;
/**
 * 
 * @author liyg
 * 2019-08-30
 * 用户驾驶证bff服务实现类
 * 
 */
@Service("drivingLicenseBffService")
public class DrivingLicenseBffServiceImpl implements DrivingLicenseBffService{
	
	private static final Logger logger = LoggerFactory.getLogger(DrivingLicenseBffServiceImpl.class);
	
	private static final String pushDrivingLicenceNotPass="push_drivingLicence_not_pass";
	private static final String pushDrivingLicencePass="push_drivingLicence_pass";
	private static final String instationDrivingLicenceNotPass="instation_drivingLicence_not_pass";
	private static final String instationDrivingLicencePass="instation_drivingLicence_pass";
	
	@Resource
	private UserBizService userBizService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private DrivingLicenseService drivingLicenseService;
	
	@Resource
	private SmsBizService smsBizService;
	
	@Resource
	private MessageCenterService messageCenterService;
	
	@Resource
	private NotifyPushService notifyPushService;
	
	@Resource
	private MessageTemplateService messageTemplateService;
	
	/**
	 * 获取驾驶证列表
	 * 
	 * @param map
	 *            参数
	 * key:userName
	 *            String 用户名 非必填
	 * key:phone
	 *            String 用户手机号 非必填
	 * key:name
	 *            String 驾驶证姓名 非必填
	 * key:status
	 *            Integer 验证状态 非必填
	 * key:pageNum
	 *            Integer 当前页
	 * key:pageSize
	 *            Integer 每页显示条数
	 * @return
	 */
	@Override
	public Paged<DrivingLicenseVo> getDrivingLicenseList(Map<String, Object> map) {
		
		//封装tab
		Paged<DrivingLicenseVo> paged=new Paged<>();
		paged=getEncapsulationTab(map,paged);
		
		Paged<DrivingLicenseBizDto> drivingLicensePaged = userBizService.getDrivingLicenseList(map);
		if(null == drivingLicensePaged) {
			return paged;
		}else if(drivingLicensePaged.isEmpty()) {
			paged.setTotal(drivingLicensePaged.getTotal());
			paged.setPageSize(drivingLicensePaged.getPageSize());
			return paged;
		}
		
		List<DrivingLicenseBizDto> drivingLicenseBizDtoList = drivingLicensePaged.getList();
		List<DrivingLicenseVo> drivingLicenseVoList = Convert.toDrivingLicenseVo(drivingLicenseBizDtoList);
		for (DrivingLicenseVo vo : drivingLicenseVoList) {
			//获取数据来源
			getDataSourceStr(vo);
		}
		
		paged.setPages(drivingLicensePaged.getPageSize());
		paged.setTotal(drivingLicensePaged.getTotal());
		paged.setList(drivingLicenseVoList);
		
		return paged;
	}
	
	/**
	 * 获取数据来源
	 * 
	 * @param vo
	 */
	private void getDataSourceStr(DrivingLicenseVo vo) {
		
		Integer status = vo.getStatus();
		
		if(DrivingLicenseStatusEnum.WAIT_PASS.getValue() == status) {
			vo.setDataSourceStr(DrivingLicenseDataSourceEnum.getName(vo.getDataSource())+"上传");
		}else{
			vo.setDataSourceStr(DrivingLicenseDataSourceEnum.getName(vo.getDataSource()));
		}
	}
	
	
	/**
	 * 封装tab
	 * @param map
	 * @param paged
	 * @return
	 */
	private Paged<DrivingLicenseVo> getEncapsulationTab(Map<String, Object> map,Paged<DrivingLicenseVo> paged){
		
		List<TabDto> tabs=Arrays.asList(null,null,null);
		DrivingLicenseStatusEnum[] values = DrivingLicenseStatusEnum.values();
		for (DrivingLicenseStatusEnum statusEnum : values) {
			TabDto tabDto = new TabDto();
			Long count = drivingLicenseService.getDrivingLicenseCountBystatus(statusEnum.getValue());
			tabDto.setCount(count.intValue());
			tabDto.setName(statusEnum.getName());
			tabDto.setType(statusEnum.getValue());
			
			if(DrivingLicenseStatusEnum.WAIT_PASS.getValue() == statusEnum.getValue()) {
				tabs.set(0, tabDto);
			}else if(DrivingLicenseStatusEnum.VERIFY_FAILURE.getValue() == statusEnum.getValue()) {
				tabs.set(1, tabDto);
			}else {
				tabs.set(2, tabDto);
			}
		}
		paged.setTab(tabs);
		return paged;
	}
	
	/**
	 * 获取用户驾驶证信息
	 * @param userId
	 * @return
	 */
	@Override
	public DrivingLicenseVo getDrivingLicense(Integer userId) {
		
		DrivingLicenseDto drivingLicenseDto = drivingLicenseService.getDrivingLicense(userId);
		DrivingLicenseVo drivingLicenseVo = Convert.toDrivingLicenseVo(drivingLicenseDto);
		if(null == drivingLicenseVo) {
			return drivingLicenseVo;
		}
		
		Integer dataSource = drivingLicenseVo.getDataSource();
		drivingLicenseVo.setDataSourceStr(DrivingLicenseDataSourceEnum.getName(dataSource));
		
		return drivingLicenseVo;
	}
	
	/**
	 * 修改驾驶证审核状态
	 * 
	 * @param vo
	 * @return
	 */
	@Override
	public Boolean modifyVerifyStatus(DrivingLicenseModifyVo vo) {
		
		DrivingLicenseBizModifyDto modifyDto=new DrivingLicenseBizModifyDto();
		BeanUtils.copyProperties(vo, modifyDto);
		UserDto user = userService.getUser(vo.getUserId());
		if(null == user) {
			throw new BizException(101, "不存在该用户信息");
		}
		Boolean flag = userBizService.modifyVerifyStatus(modifyDto);
		if(flag) {
			//发送短信
			sendNote(user.getPhone(),vo.getVerifyStatus());
			//驾驶证人工审核提醒消息推送
			sendPush(user.getId(),user.getPhone(),vo.getVerifyStatus());
		}
		return flag;
	}
	
	/**
	 *驾驶证人工审核提醒发送短信
	 * @param userVo
	 */
	private void sendNote(String phone,Integer verifyStatus) {
	    try {
	    	if(DrivingLicenseVerifyStatusEnum.APPROVE.getValue() == verifyStatus) {
	    		smsBizService.sendMessage(phone, SmsTemplateEnum.DRIVING_AUDIT_PASS.getValue(), null, null);
	    	}else if(DrivingLicenseVerifyStatusEnum.REJECT.getValue() == verifyStatus) {
	    		smsBizService.sendMessage(phone, SmsTemplateEnum.DRIVING_AUDIT_REJECT.getValue(), null, null);
	    	}
		} catch (Exception e) {
			logger.error("驾驶证人工审核提醒发送短信失败",e);
		}
	}
	
	/**
	 * 驾驶证人工审核提醒消息推送
	 * @param userId
	 * @param phone
	 * @param verifyStatus
	 */
	private void sendPush(Integer userId,String phone,Integer verifyStatus) {
		try {
			Map<String, MessageTemplateDto> map = getByKeys();
			if(null != map) {
				//psuh
				NotifyPushCreateDto notifyPush = getNotifyPush( phone, verifyStatus,map);
				notifyPushService.notifyPushByAlias(notifyPush);
				//保存站内信息
				MessageCenterCreateDto messageCenter = getMessageCenter( userId, verifyStatus,map);
				messageCenterService.createMessageCenter(messageCenter);
			}
		} catch (Exception e) {
			logger.error("驾驶证人工审核提醒消息推送失败",e);
		}
		
	}
	
	/**
	 * 获取instation实体
	 * @param userId
	 * @param verifyStatus
	 * @param map
	 * @return
	 */
	private MessageCenterCreateDto getMessageCenter(Integer userId,Integer verifyStatus,Map<String,MessageTemplateDto> map) {
		MessageCenterCreateDto dto =new MessageCenterCreateDto();
		dto.setUserId(userId);
		MessageTemplateDto messageTemplateDto =null;
		if(DrivingLicenseVerifyStatusEnum.APPROVE.getValue() == verifyStatus) {
			messageTemplateDto = map.get(instationDrivingLicencePass);
    	}else if(DrivingLicenseVerifyStatusEnum.REJECT.getValue() == verifyStatus) {
    		messageTemplateDto = map.get(instationDrivingLicenceNotPass);
    	}
		dto.setTitle(messageTemplateDto.getSubject());
		dto.setMessage(messageTemplateDto.getBody());
		dto.setType(MessageCenterTypeEnum.DRIVING_LICENSE_AUDIT_NOTICE.getValue());
		dto.setStatus(MessageCenterStatusEnum.UNREAD.getValue());
		return dto;
	}
	
	/**
	 * 获取psuh实体
	 * @param phone
	 * @param verifyStatus
	 * @param map
	 * @return
	 */
	private NotifyPushCreateDto getNotifyPush(String phone,Integer verifyStatus,Map<String,MessageTemplateDto> map) {
		NotifyPushCreateDto dto =new NotifyPushCreateDto();
		ArrayList<String> alias = new ArrayList<>(1);
		alias.add(phone);
		dto.setAlias(alias);
		MessageTemplateDto messageTemplateDto =null;
		if(DrivingLicenseVerifyStatusEnum.APPROVE.getValue() == verifyStatus) {
			messageTemplateDto = map.get(pushDrivingLicencePass);
    	}else if(DrivingLicenseVerifyStatusEnum.REJECT.getValue() == verifyStatus) {
    		messageTemplateDto = map.get(pushDrivingLicenceNotPass);
    	}
		dto.setNotifyTitle(messageTemplateDto.getSubject());
		dto.setMsgTitle(messageTemplateDto.getSubject());
		dto.setIosMsgContent(messageTemplateDto.getBody());
		dto.setAndroidMsgContent(messageTemplateDto.getBody());
		return dto;
	}
	
	/**
	 * 查询模板信息
	 * @return
	 */
	private Map<String,MessageTemplateDto> getByKeys(){
		List<String> keys= new ArrayList<>();
	    keys.add(pushDrivingLicenceNotPass);
	    keys.add(pushDrivingLicencePass);
	    keys.add(instationDrivingLicenceNotPass);
	    keys.add(instationDrivingLicencePass);
	    try {
	    	 Map<String,MessageTemplateDto> map = messageTemplateService.getByKey(keys);
	    	 return map;
		} catch (Exception e) {
			logger.error("查询消息模板异常",e);
			return null;
		}
	}
	
}
